﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GeoTrans;
using Microsoft.WindowsMobile.Samples.Location;
using GpSpotMe.Ign.TileModel;
using WinTest.GpSpotMe.Ign.TileModel;

namespace GpSpotMe
{
    public partial class MainForm : Form
    {
        private Gps gps = new Gps();
        private GpsDeviceState device = null;
        private GpsPosition position = null;
        //private Converter conv = new Converter();
        private EventHandler updateDataDelegate =null;
        private double utmX=0;
        private double utmY=0;

        //private Graphics gr;
        private Bitmap mapa = new Bitmap(512, 512);

        public MainForm()
        {
            InitializeComponent();
            pictBox.Image = mapa;

            gps.DeviceStateChanged += new DeviceStateChangedEventHandler(gps_DeviceStateChanged);
            gps.LocationChanged += new LocationChangedEventHandler(gps_LocationChanged);
            updateDataDelegate = new EventHandler(updateData);
        }

        void gps_LocationChanged(object sender, LocationChangedEventArgs args)
        {
            position = args.Position;
            //Invoke(updateDataDelegate);
        }

        void gps_DeviceStateChanged(object sender, DeviceStateChangedEventArgs args)
        {
            device = args.DeviceState;
            //Invoke(updateDataDelegate);
        }

        /// <summary>
        /// Actualiza la informacion mostrada
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void updateData(object sender, EventArgs e)
        {
            if (!gps.Opened) return;
            switch (tabControl1.SelectedIndex)
            {
                case 0://Pg de posicion
                    {

                            StringBuilder sb = new StringBuilder();
                            if (device != null)
                            {
                                sb.Append(device.FriendlyName + "; " + device.ServiceState + ", " + device.DeviceState + "\n\n");
                            }

                            if (position != null)
                            {
                                if (position.PositionDilutionOfPrecisionValid
                                    && position.VerticalDilutionOfPrecisionValid && position.HorizontalDilutionOfPrecisionValid)
                                {
                                    sb.AppendFormat("DLOP: H: {0} V:{1} P:{2}\n", position.HorizontalDilutionOfPrecision,
                                        position.VerticalDilutionOfPrecision, position.PositionDilutionOfPrecision);
                                }

                                if (position.LatitudeValid)
                                {
                                    sb.Append("Latitude (DD):   " + position.Latitude.ToString("F5") + "\n");
                                    sb.Append("Latitude (D,M,S):   " + position.LatitudeInDegreesMinutesSeconds + "\n");

                                }

                                if (position.LongitudeValid)
                                {
                                    sb.Append("Longitude (DD):   " + position.Longitude.ToString("F5") + "\n");
                                    sb.Append("Longitude (D,M,S):   " + position.LongitudeInDegreesMinutesSeconds + "\n");
                                }

                                if (position.EllipsoidAltitudeValid)
                                {
                                    sb.Append("EllipsoidAltitude:   " + position.EllipsoidAltitude.ToString("F2") + "\n");
                                }

                                if (position.HeadingValid)
                                {
                                    sb.AppendFormat("Heading : {0}; {1}\n", position.Heading.ToString("F2"), direction(position.Heading));
                                }
                                if (position.SpeedValid)
                                {
                                    sb.AppendFormat("Speed : {0} km/h {1}; m/s \n", (position.Speed * 1.852).ToString("F2"), (position.Speed * 0.514).ToString("F2"));
                                }

                                if (position.SatellitesInViewCountValid &&
                                    position.SatelliteInSolutionCountValid)
                                {
                                    sb.AppendFormat("Satellite Count: {0}/{1} \n", position.SatelliteInSolutionCount,
                                        position.SatellitesInViewCount);
                                }

                                if (position.TimeValid)
                                {
                                    sb.Append("Time:   " + position.Time.ToString() + "\n");
                                }
                                if (position.LatitudeValid && position.LongitudeValid )
                                {
                                    double easting, northing;
                                    Converter.PolarWGS84ToUTMinED50(position.Latitude, position.Longitude, 0, out easting, out northing);
                                    sb.AppendFormat("UTM; X:{0}, Y:{1}  \n", easting.ToString("F1"), northing.ToString("F1"));
                                    utmX = easting;
                                    utmY = northing;
                                }
                            }
                            lbPosition.Text = sb.ToString();

                        return;
                    }                    
                case 1://Satelites
                    {
                        if (position.SatellitesInSolutionValid &&
                                    position.SatellitesInViewValid)
                        {
                            dsSatellites.Satellites.Clear();
                            foreach (Satellite sat in position.SatellitesInView)
                            {
                                dsSatellites.Satellites.AddSatellitesRow(sat.Id, sat.Azimuth, sat.Elevation, sat.SignalStrength,
                                Array.IndexOf(position.SatellitesInSolution, sat) > -1);
                            }
                        }
                        return;
                    }
                default:
                    break;
            }            
        }

        private string direction(double heading)
        {
            double hc = heading + 22.5;
            int d = (int)Math.Floor(hc / 45.0);
            switch (d)
            {
                case 0: return "N";
                case 1: return "NE";
                case 2: return "E";
                case 3: return "SE";
                case 4: return "S";
                case 5: return "SO";
                case 6: return "O";
                case 7: return "NO";
                case 8: return "N";
                default: return string.Empty;
            }            
        }

        private void menuItemStartGps_Click(object sender, EventArgs e)
        {
            if (!gps.Opened)
            {
                gps.Open();
            }
            timer.Enabled = true;
            menuItemStartGps.Enabled = false;
            menuItemStopGps.Enabled = true;
        }

        private void menuItemStopGps_Click(object sender, EventArgs e)
        {
            if (gps.Opened)
            {
                gps.Close();
            }
            timer.Enabled = false;
            menuItemStartGps.Enabled = true;
            menuItemStopGps.Enabled = false;
        }

        private void menuItemExit_Click(object sender, EventArgs e)
        {
            if (gps.Opened)
            {
                gps.Close();
            }
            this.Close();
        }

        private void MainForm_Closing(object sender, CancelEventArgs e)
        {
            if (gps.Opened)
            {
                gps.Close();
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            if (gps.Opened)
            {
                menuItemStartGps.Enabled = false;
                menuItemStopGps.Enabled = true;
            }
            else
            {
                menuItemStartGps.Enabled = true;
                menuItemStopGps.Enabled = false;
            }
            using (Graphics gr = Graphics.FromImage(mapa))
            {
                gr.FillRectangle(new SolidBrush(Color.Aqua), 0, 0, mapa.Height, mapa.Width);
            }
            pictBox.Invalidate();             
        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
           //updateData(this, new EventArgs());
           Invoke(updateDataDelegate);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //updateData(this, new EventArgs());
            Invoke(updateDataDelegate);
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            Point utmP = new Point((int)utmX, (int)utmY);
            IgnMap map = new IgnMap(utmP, 200, 2);
            using (Graphics gr = Graphics.FromImage(mapa))
            {
                gr.DrawImage(map.Bmp, 0, 0);
            }   
            pictBox.Invalidate();
        }



    }
}